
#include <QXmlStreamReader>
#include <QFile>

#include "Agence.h"

Agence Agence::Get()
{
	Agence a;
	QFile file("xml/agence.xml");

	if(file.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		QXmlStreamReader reader(&file);	
		while(!reader.atEnd())
		{
			QXmlStreamReader::TokenType token = reader.readNext();
			
			if(token == QXmlStreamReader::StartDocument)
				continue;
			
			if(token == QXmlStreamReader::StartElement)
			{
				reader.readNext();
				while(!(reader.tokenType() == QXmlStreamReader::EndElement 
							&& reader.name() == "agence"))
				{
					QXmlStreamReader::TokenType token = reader.readNext();

					if(token == QXmlStreamReader::EndElement)
						continue;

					if(reader.name() == "nbRendezVousTotal")
					{
						reader.readNext();
						a.SetNbRendezVousTotal(reader.text().toString().toInt());
					}

					if(reader.name() == "nbRendezVousSucces")
					{
						reader.readNext();
						a.SetNbRendezVousSucces(reader.text().toString().toInt());
					}
				}
			}
		}
		reader.clear();	
		file.close();
	}
	return a;
}

void Agence::Save(Agence a)
{
	QFile* file = new QFile("xml/agence.xml");

	if(file->open(QIODevice::WriteOnly | QIODevice::Text))
	{
		QXmlStreamWriter* writer = new QXmlStreamWriter(file);
		writer->setAutoFormatting(true);

		writer->writeStartDocument(); // XML header
		writer->writeStartElement("agence");

		writer->writeTextElement("nbRendezVousTotal", QString("%1").arg(a.GetNbRendezVousTotal()));
		writer->writeTextElement("nbRendezVousSucces", 
				QString("%1").arg(a.GetNbRendezVousSucces()));

		writer->writeEndElement();	// </clients>
		writer->writeEndDocument();
		file->close();
	}
}
